package utils

import (
	"sync"
	"time"
)

type WaitGroup struct {
	sync.WaitGroup
	restartTime int
	stopTask    bool
	stopChan    chan bool
}

//创建一个协程任务
func (w *WaitGroup) Wrap(cb func()) {
	w.Add(1)
	go func() {
		cb()
		w.Done()
	}()
}

//创建一个后台协程任务
func (w *WaitGroup) Task(tf func() time.Duration) {
	if w.stopChan == nil {
		w.stopChan = make(chan bool)
	}

	w.Add(1)
	go func() {
	TaskFor:
		for !w.stopTask {
			t := tf()
			if int(t) == 0 {
				//间隔时间为0，可能发生了故障事件，每次重试在原来的时间上加5分钟
				w.restartTime += 5
				t = time.Duration(w.restartTime) * time.Minute
			} else {
				w.restartTime = 0
			}

			select {
			case <-w.stopChan:
				break TaskFor
			case <-time.After(t):
			}
		}
		w.Done()
	}()
}

//停止运行中的任务
func (w *WaitGroup) StopTask() {
	if !w.stopTask {
		if w.stopChan == nil {
			w.stopChan = make(chan bool)
		}

		w.stopTask = true

		close(w.stopChan)
	}
}
